package com.czmh.etc.onlinepubsys.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czmh.etc.onlinepubsys.dto.EtcOrderListDTO;
import com.czmh.etc.onlinepubsys.entity.WeiXinPayRefund;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.enums.WeixinTradeStateEnum;
import com.czmh.etc.onlinepubsys.exceptions.EtcMsgException;
import com.czmh.etc.onlinepubsys.json.JsonResult;
import com.czmh.etc.onlinepubsys.maper.EtcOrderMapper;
import com.czmh.etc.onlinepubsys.maper.EtcPayOrderMapper;
import com.czmh.etc.onlinepubsys.maper.EtcWechatrefundorderMapper;
import com.czmh.etc.onlinepubsys.model.EtcPayOrder;
import com.czmh.etc.onlinepubsys.model.EtcWechatrefundorder;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.utils.JsonResultUtil;
import com.czmh.etc.onlinepubsys.utils.WeiXinPayUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * ETC支付订单表 服务实现类
 * </p>
 *
 * @author eric
 * @since 2021-11-10
 */
@Service
@Log4j2
public class EtcPayOrderServiceImpl extends ServiceImpl<EtcPayOrderMapper, EtcPayOrder> implements EtcPayOrderService {
    @Value("${wx.appid}")
    private String                      appid;
    @Value("${wx.wxPayMch_id}")
    private String                      mch_id;
    @Value("${wx.wxPayunifiedorderUrl}")
    private String                      payunifiedorderUrl;
    @Value("${wx.payRefundUrl}")
    private String                      payRefundUrl;
    @Value("${wx.wxPayAppSecret}")
    private String                      wxPayAppSecret;
    @Value("${wx.wxPayNotifyUrl}")
    private String                      wxPayNotifyUrl;
    @Value("${wx.wxPayRefundNotifyUrl}")
    private String                      wxPayRefundNotifyUrl;
    @Value("${wx.certpath}")
    private String                      certpath;
    @Value("${etc.obuCash}")
    private String                      obuCash;

    @Autowired
    private EtcWechatrefundorderMapper etcWechatrefundorderMapper;

    @Autowired
    EtcOrderMapper etcOrderMapper;

    @Override
    public List<EtcOrderListDTO> queryOrderList(Map<String, Object> map) {
        return etcOrderMapper.queryOrderList(map);
    }

    @Override
    public JsonResult refundWxPayOrder(String orderNo, String userId) throws Exception {
        QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
        lambda.eq(EtcPayOrder::getDeleteFlag, 0);
        lambda.eq(EtcPayOrder::getOrderNo, orderNo);
        EtcPayOrder etcPayOrder = getOne(wrapper, false);
        if(etcPayOrder == null){
            log.info("退款申请失败-找不到对应的订单信息:{}", orderNo);
            JsonResultUtil.toErrorResult("退款申请失败-找不到对应的订单信息");
        }
        Integer payRefundFee = etcPayOrder.getAmount();
        WeiXinPayRefund weiXinPayRefund = new WeiXinPayRefund();
        weiXinPayRefund.setAppid(appid);
        weiXinPayRefund.setMchId(mch_id);
        weiXinPayRefund.setNotifyUrl(wxPayRefundNotifyUrl);
        weiXinPayRefund.setOutRefundNo(orderNo);
        weiXinPayRefund.setOutTradeNo(orderNo);
        weiXinPayRefund.setRefundFee(payRefundFee);
        weiXinPayRefund.setTotalFee(payRefundFee);
        String data = WeiXinPayUtils.getPayRefundXml(weiXinPayRefund, wxPayAppSecret);
        // 调用微信支付的功能,获取微信支付code_url
        String xmlStr = WeiXinPayUtils.doRefund(payRefundUrl, data, mch_id, certpath);
        log.info("返回的xml信息：" + xmlStr);
        Map<String, Object> payRefundResponse = com.czmh.etc.onlinepubsys.utils.mingchuang.PayUtil.getMapFromXML(xmlStr);
        log.info("返回的map信息：" + JSON.toJSONString(payRefundResponse));
        // 保存退款申请记录
        if(WeixinTradeStateEnum.SUCCESS.name().equals(payRefundResponse.get("return_code")) && WeixinTradeStateEnum.SUCCESS.name().equals(payRefundResponse.get("result_code"))){
            // 保存退款申请记录
            EtcWechatrefundorder etcWechatrefundorder = JSON.parseObject(JSON.toJSONString(payRefundResponse), EtcWechatrefundorder.class);
            try {
                EtcWechatrefundorder etcWechatrefundorder1 = etcWechatrefundorderMapper.getById(etcWechatrefundorder.getRefund_id());
                if(etcWechatrefundorder1 == null){
                    //微信退款成功之后更新etc_pay_order状态pay_state为6
                    if (null != etcPayOrder){
                        etcPayOrder.setPayState(6);
                        etcPayOrder.setRefundNo(etcWechatrefundorder.getTransaction_id());
                        etcPayOrder.setRefundTime(new Date());
                        updateById(etcPayOrder);
                        log.info("微信退款成功之后更新etc_pay_order状态为6已退款：" + JSON.toJSONString(etcPayOrder));
                    }else{
                        log.info("微信退款成功之后更新etc_pay_order状态为6已退款：" + "记录为NULL");
                    }
                    //保存退款申请记录
                    etcWechatrefundorderMapper.insert(etcWechatrefundorder);
                }else {
                    return JsonResultUtil.toResult("您已退款申请成功！");
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("保存退款申请记录失败：" + JSON.toJSONString(etcWechatrefundorder));
                etcPayOrder.setPayState(7);
                //请求信息附加到扩展字段
                String jsonStr = etcPayOrder.getJsonData();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject == null) {
                    jsonObject = new JSONObject();
                }
                jsonObject.put("payRefundResponse", payRefundResponse);
                etcPayOrder.setJsonData(jsonObject.toJSONString());
                etcPayOrder.setRefundTime(new Date());
                updateById(etcPayOrder);
            }
            return JsonResultUtil.toResult("退款申请成功！");
        }
        etcPayOrder.setPayState(7);
        //请求信息附加到扩展字段
        String jsonStr = etcPayOrder.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        jsonObject.put("payRefundResponse", payRefundResponse);
        etcPayOrder.setJsonData(jsonObject.toJSONString());
        etcPayOrder.setRefundTime(new Date());
        updateById(etcPayOrder);
        return JsonResultUtil.toErrorResult("退款申请失败，请联系管理员！");
    }
}
